//
//  rect_3d.cpp
//  OpenLearn
//
//  Created by korion chen on 2020/3/27.
//  Copyright © 2020 korion. All rights reserved.
//

#include <iostream>
#include "header/rect_3d.hpp"
#include "header/model.h"

const float Rect3D::vertices[] = {
     0.5f,  0.5f, 0.0f,   1.0f, 1.0f, // top right
     0.5f, -0.5f, 0.0f,   1.0f, 0.0f, // bottom right
    -0.5f, -0.5f, 0.0f,   0.0f, 0.0f, // bottom left
    -0.5f,  0.5f, 0.0f,   0.0f, 1.0f  // top left
};

const int Rect3D::indices[] = {
    0, 1, 3,
    1, 2, 3
};

const char* Rect3D::vertex_shader_code = ""
    "#version 330 core\n"
    "in vec3 Pos;\n"
    "in vec2 texPod;\n"
    "\n"
    "out vec2 TexCoord;\n"
    "\n"
    "uniform mat4 model;\n"
    "uniform mat4 view;\n"
    "uniform mat4 projection;\n"
    "\n"
    "void main()\n"
    "{\n"
    "    gl_Position = projection * view * model * vec4(Pos, 1.0);\n"
    "    TexCoord = vec2(texPod.x, texPod.y);\n"
    "}\n";

const char* Rect3D::fragment_shader_code = ""
    "#version 330 core\n"
    "out vec4 FragColor;\n"
    "\n"
    "in vec2 TexCoord;\n"
    "\n"
    "uniform sampler2D texture0;\n"
    "uniform sampler2D texture1;\n"
    "\n"
    "void main()\n"
    "{\n"
    "    FragColor = mix(texture(texture0, TexCoord), texture(texture1, TexCoord), 0.2);\n"
    "}\n";

int Rect3D::createShader(int type, const char *code){
    int shader = glCreateShader(type);
    glShaderSource(shader, 1, &code, NULL);
    glCompileShader(shader);
    int success;
    glGetShaderiv(shader, GL_COMPILE_STATUS, &success);
    if (!success) {
        char info[512];
        glGetShaderInfoLog(shader, 512, NULL, info);
        std::cout << "ERROR::SHADER::COMPILATION_FAILED\n"<< info << std::endl;
        return 0;
    }
    return shader;
}

int Rect3D::createProgram(){
    int vertexShader = createShader(GL_VERTEX_SHADER, vertex_shader_code);
    int fragmentShader = createShader(GL_FRAGMENT_SHADER, fragment_shader_code);
    if (!vertexShader || !fragmentShader) {
        return 0;
    }
    uint32_t program = glCreateProgram();
    glAttachShader(program, vertexShader);
    glAttachShader(program, fragmentShader);
    glLinkProgram(program);
    int success;
    glGetProgramiv(program, GL_LINK_STATUS, &success);
    if (!success) {
        char info[512];
        glGetProgramInfoLog(program, 512, NULL, info);
        std::cout << "ERROR::SHADER::PROGRAM::LINKING_FAILED\n"<< info << std::endl;
        return 0;
    }
    glDeleteShader(vertexShader);
    glDeleteShader(fragmentShader);
    return program;
}

int Rect3D::loadTexture(const char *path, bool reverseY){
    ImageData *data = new ImageData(path);
    bool result = data->loadData(reverseY);
    if (!result) {
        delete(data);
        std::cout << "LOAD IMAGE FAIL" << std::endl;
        return 0;
    }
    uint32_t texture;
    glGenTextures(1, &texture);
    glBindTexture(GL_TEXTURE_2D, texture);
    
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    
    if (data->nrChannels == 3){
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, data->width, data->height, 0, GL_RGB, GL_UNSIGNED_BYTE, data->data);
    } else {
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, data->width, data->height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data->data);
    }
    glGenerateMipmap(GL_TEXTURE_2D);
    glBindTexture(GL_TEXTURE_2D, NULL);
    delete(data);
    return texture;
}

bool Rect3D::init(int width, int height){
    this->width = width;
    this->height = height;
    
    mProgram = createProgram();
    if (!mProgram) {
        return false;
    }
    glGenVertexArrays(1, &context);
    glBindVertexArray(context);
    
    glGenBuffers(1, &verticesBuffer);
    glBindBuffer(GL_ARRAY_BUFFER, verticesBuffer);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
    
    int pos = glGetAttribLocation(mProgram, "Pos");
    glVertexAttribPointer(pos, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)0);
    glEnableVertexAttribArray(pos);
      
    int texPod = glGetAttribLocation(mProgram, "texPod");
    glVertexAttribPointer(texPod, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)(3 * sizeof(float)));
    glEnableVertexAttribArray(texPod);
    
    glGenBuffers(1, &indicesBuffer);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indicesBuffer);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
        
    glBindVertexArray(NULL);
    glBindBuffer(GL_ARRAY_BUFFER, NULL);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, NULL);
    
    texture0 = loadTexture("/Users/korionchen/WorkSpace/person/OpenGLlearn/OpenLearn/OpenLearn/res/container.jpg", false);
       
    texture1 = loadTexture("/Users/korionchen/WorkSpace/person/OpenGLlearn/OpenLearn/OpenLearn/res/awesomeface.png", true);
    
    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, texture0);
    glActiveTexture(GL_TEXTURE1);
    glBindTexture(GL_TEXTURE_2D, texture1);

    hasInit = true;
    return true;
}

void Rect3D::drawSelf(GLFWwindow *window, float var1, float var2){
    if (!hasInit) {
        return;
    }
    glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT);
    glUseProgram(mProgram);
    glUniform1i(glGetUniformLocation(mProgram, "texture0"), 0);
    glUniform1i(glGetUniformLocation(mProgram, "texture1"), 1);
    
    model = glm::rotate(glm::mat4(1.0f), glm::radians(-90.0f * var1), glm::vec3(1.0f, 0.0f, 0.0f));
    model = glm::rotate(model, glm::radians(90.0f * var2), glm::vec3(0.0f, 0.1f, 0.0f));
    
    view = glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, 0.0f, -3.0f));
    projection = glm::perspective(glm::radians(45.0f), (float)width/(float)height, 0.1f, 100.0f);

    glUniformMatrix4fv(glGetUniformLocation(mProgram, "model"), 1, GL_FALSE, glm::value_ptr(model));
    glUniformMatrix4fv(glGetUniformLocation(mProgram, "view"), 1, GL_FALSE, glm::value_ptr(view));
    glUniformMatrix4fv(glGetUniformLocation(mProgram, "projection"), 1, GL_FALSE, glm::value_ptr(projection));
    
    glBindVertexArray(context);
    glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
    glfwSwapBuffers(window);
}

void Rect3D::destroy(){
    glDeleteVertexArrays(1, &context);
    glDeleteBuffers(1, &verticesBuffer);
    glDeleteBuffers(1, &indicesBuffer);
}
